#!/system/bin/sh

dir=${0%/*}
tmpLspdApk="/data/local/tmp/daemon.apk"
debug=@DEBUG@
flavor=@FLAVOR@

if [ -r $tmpLspdApk ]; then
  java_options="-Djava.class.path=$tmpLspdApk"
  debug="true"
else
  java_options="-Djava.class.path=$dir/daemon.apk"
fi

if [ $debug = "true" ]; then
  os_version=$(getprop ro.build.version.sdk)
  if [ "$os_version" -eq "27" ]; then
    java_options="$java_options -Xrunjdwp:transport=dt_android_adb,suspend=n,server=y -Xcompiler-option --debuggable"
  elif [ "$os_version" -eq "28" ]; then
    java_options="$java_options -XjdwpProvider:adbconnection -XjdwpOptions:suspend=n,server=y -Xcompiler-option --debuggable"
  else
    java_options="$java_options -XjdwpProvider:adbconnection -XjdwpOptions:suspend=n,server=y"
  fi
fi

mount tmpfs -t tmpfs /data/resource-cache

if [ ! -S "/dev/socket/zygote" ]; then
  timeout 0.5 inotifyd - /dev/socket:near | while read -r line; do
    $debug && log -p v -t "LSPosed" "inotify: $line"
    if [ -S "/dev/socket/zygote" ]; then
      $debug && log -p v -t "LSPosed" "zygote started"
      touch /dev/socket&
      exit
    fi
  done
fi
$debug && log -p d -t "LSPosed" "start $flavor daemon $*"

# shellcheck disable=SC2086
exec /system/bin/app_process $java_options /system/bin --nice-name=lspd org.lsposed.lspd.Main "$@" >/dev/null 2>&1
